/*
 * @lc app=leetcode.cn id=126 lang=cpp
 *
 * [126] 单词接龙 II
 */

// @lc code=start
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
    bool check(const string &target, const string &word)
    {
        bool diff = false;
        for (int i = 0; i < target.size(); i++)
        {
            if (target[i] != word[i])
            {
                if (diff)
                    return false;
                diff = true;
            }
        }
        return diff;
    }
    set<string> neighbor(const set<string> &words, const string &target)
    {
        set<string> ans;
        for (const auto &s : words)
        {
            if (check(target, s))
            {
                ans.insert(s);
            }
        }
        return ans;
    }
    vector<vector<string>> findLadders(string beginWord, string endWord, vector<string> &wordList)
    {

        set<string> words;
        for (const auto &s : wordList)
        {
            words.insert(s);
        }

        vector<set<string>> seq;
        vector<vector<string>> ans;
        seq.push_back({beginWord});
        words.erase(beginWord);

        while (words.size())
        {
            auto &v = *(seq.end() - 1);
            set<string> next;
            for (auto &w : v)
            {
                auto tmp = neighbor(words, w);
                next.insert(tmp.begin(), tmp.end());
            }
            if(next.size() == 0) break;
            for (auto &w : next)
            {
                words.erase(w);
            }
            if (next.find(endWord) != next.end())
            {
                seq.push_back({endWord});
                break;
            }
            seq.push_back(next);
        }

        auto &end_s = *(seq.end() - 1);
        if (end_s.find(endWord) != end_s.end())
        {
            //从后向前查找
            ans.push_back({endWord});
            for (int i = seq.size() - 2; i >= 0; i--)
            {
                set<string> &words = seq[i];
                const size_t ans_size = ans.size();
                for (int j = 0; j < ans_size; j++)
                {
                    vector<string> v = ans[j];
                    auto tmp = neighbor(words, *(v.end() - 1));
                    for (auto it = ++tmp.begin(); it != tmp.end(); it++)
                    {
                        ans.push_back(v);
                        (ans.end() - 1)->push_back(*it);
                    }
                    ans[j].push_back(*tmp.begin());
                }
            }
        }

        for(auto& v:ans)
        {
            reverse(v.begin(), v.end());
        }

        return ans;
    }
};

// int main()
// {
//     vector<string> words = {"hot","dog"};
//     Solution().findLadders("hit", "dog", words);
//     return 0;
// }

// @lc code=end
